<template>
  <div>
    <div class="search">
      <input v-model="info" class="search-input" type="text" name="" id="" placeholder="输入城市名或拼音">
    </div>
    <div class="srarch-content" ref="search" v-show="info">
      <ul>
        <li class="search-keywrod border-bottom" v-for="city in list" :key="city.id" @click='handleCity(city.name)'>{{city.name}}</li>
        <li class="search-keywrod border-bottom" v-show="!list.length">没有找到匹配城市</li>
      </ul>
    </div>
  </div>
</template>
<script>
import Bscroll from 'better-scroll'
export default {
  name: 'citySearch',
  props: {
    msg: Object
  },
  data () {
    return {
      info: '',
      timer: null,
      list: []
    }
  },
  methods: {
    handleCity (city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
      this.info = ''
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search, {click: true})
  },
  updated () {
    this.scroll && this.scroll.refresh()
  },
  activated () {
    this.scroll && this.scroll.refresh()
  },
  watch: {
    info () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.info) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.msg.cities) {
          this.msg.cities[i].forEach((val) => {
            if (val.spell.indexOf(this.info) > -1 || val.name.indexOf(this.info) > -1) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>
<style lang="stylus" scoped>
.search
  width: 100%
  padding: 0 .1rem
  box-sizing: border-box
  text-align: center
  line-height: .86rem
  background: #00bcd4
  .search-input
    padding: 0 .1rem
    width: 100%
    height 0.65rem
    text-align: center
    border-radius: .06rem
    box-sizing: border-box
.srarch-content
  overflow hidden
  position absolute
  top 1.72rem
  left: 0
  right: 0
  bottom :0
  z-index 1
  background: #eee
  .search-keywrod
    line-height: .62rem
    text-indent: .2rem
    color #666
    background: #fff
</style>
